import exifread
import json
import urllib.request
import os
from pathlib import Path
from PIL import Image
from datetime import datetime
import imagehash  # 需要先安装：pip install ImageHash
from collections import defaultdict

def process_image(image_path):
    try:
        # 首先尝试读取EXIF信息
        with open(image_path, 'rb') as f:
            tags = exifread.process_file(f)
        print("===========================================")    
        print(f'\n处理图片: {image_path}')
        
        if not tags:
            print('未找到EXIF信息，显示基本文件信息：')
            # 获取文件创建时间
            creation_time = os.path.getctime(image_path)
            # 获取文件修改时间
            modified_time = os.path.getmtime(image_path)
            
            creation_date = datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d %H:%M:%S')
            modified_date = datetime.fromtimestamp(modified_time).strftime('%Y-%m-%d %H:%M:%S')
            
            print('创建时间：', creation_date)
            print('修改时间：', modified_date)
            
            # 获取图片分辨率
            with Image.open(image_path) as img:
                width, height = img.size
                print(f'照片尺寸：{width} x {height}')
            return
                
        # 如果有EXIF信息，显示原有的详细信息
        print('拍摄时间：', tags.get('EXIF DateTimeOriginal', 'Unknown'))
        print('照相机制造商：', tags.get('Image Make', 'Unknown'))
        print('照相机型号：', tags.get('Image Model', 'Unknown'))
        print('照片尺寸：', tags.get('EXIF ExifImageWidth', 'Unknown'), 
              tags.get('EXIF ExifImageLength', 'Unknown'))
        
        lat = getLatOrLng(tags,'GPS GPSLatitudeRef','GPS GPSLatitude')
        lng = getLatOrLng(tags,'GPS GPSLongitudeRef','GPS GPSLongitude')
        if lat and lng:
            print('纬度:{} 经度：{}'.format(lat, lng))
            
    except Exception as e:
        print(f'处理图片时出错 {image_path}: {str(e)}')

#获取经度或纬度
def getLatOrLng(tags, refKey, tudeKey):
  if refKey not in tags:
    return None
  ref=tags[refKey].printable
  LatOrLng=tags[tudeKey].printable[1:-1].replace(" ","").replace("/",",").split(",")
  LatOrLng=float(LatOrLng[0])+float(LatOrLng[1])/60+float(LatOrLng[2])/float(LatOrLng[3])/3600
  if refKey == 'GPS GPSLatitudeRef' and tags[refKey].printable != "N":
    LatOrLng=LatOrLng*(-1)
  if refKey == 'GPS GPSLongitudeRef' and tags[refKey].printable != "E":
    LatOrLng=LatOrLng*(-1)
  return LatOrLng

#调用百度地图API通过经纬度获取位置
def getlocation(lat,lng):  
  url = 'http://api.map.baidu.com/geocoder/v2/?location=' + lat + ',' + lng + '&output=json&pois=1&ak=申请的百度地图KEY'
  req = urllib.request.urlopen(url)
  res = req.read().decode("utf-8") 
  str = json.loads(res)
  #print(str)
  jsonResult = str.get('result')
  formatted_address = jsonResult.get('formatted_address')
  return formatted_address

class ImageStats:
    def __init__(self):
        self.total_count = 0
        self.format_counts = {}  # 统计不同格式的数量
        self.directory_counts = {}  # 统计每个目录的数量
        self.image_hashes = defaultdict(list)  # 存储图片哈希值
    
    def add_image(self, image_path):
        self.total_count += 1
        # 统计格式
        ext = os.path.splitext(image_path)[1].lower()
        self.format_counts[ext] = self.format_counts.get(ext, 0) + 1
        # 统计目录
        directory = os.path.dirname(image_path)
        self.directory_counts[directory] = self.directory_counts.get(directory, 0) + 1
        # 计算图片哈希
        try:
            with Image.open(image_path) as img:
                # 使用感知哈希算法
                hash_value = str(imagehash.average_hash(img))
                self.image_hashes[hash_value].append(image_path)
        except Exception as e:
            print(f"计算图片哈希出错 {image_path}: {str(e)}")
    
    def print_stats(self):
        print("\n========== 照片统计信息 ==========")
        print(f"总照片数量: {self.total_count}")
        
        print("\n各格式照片数量:")
        for ext, count in self.format_counts.items():
            print(f"{ext}: {count} 张")
        
        print("\n各目录照片数量:")
        for directory, count in self.directory_counts.items():
            print(f"{directory}: {count} 张")
            
        print("\n相同照片检测结果:")
        duplicate_found = False
        for hash_value, paths in self.image_hashes.items():
            if len(paths) > 1:
                duplicate_found = True
                print(f"\n发现 {len(paths)} 张相同的照片:")
                for path in paths:
                    print(f"  - {path}")
        
        if not duplicate_found:
            print("未发现相同的照片")

def main():
    image_dir = 'D:/360MoveData/Users/Hao_MateBook/Desktop/python/照片'
    print(f'开始扫描目录: {image_dir}')
    
    if not os.path.exists(image_dir):
        print(f'错误：目录 "{image_dir}" 不存在！')
        return
        
    # 支持的图片格式
    image_extensions = ('.jpg', '.jpeg', '.tiff', '.nef', '.cr2')
    
    # 创建统计对象
    stats = ImageStats()
    
    # 遍历目录
    for root, dirs, files in os.walk(image_dir):
        print(f'扫描子目录: {root}')
        for file in files:
            if file.lower().endswith(image_extensions):
                image_path = os.path.join(root, file)
                print(f'找到图片文件: {file}')
                process_image(image_path)
                stats.add_image(image_path)
    
    # 打印统计信息
    stats.print_stats()

# location = getlocation(str(lat), str(lng))
# print('位置：{}'.format(location))

if __name__ == "__main__":
    main()

